"""
通知服务工具类
"""
import logging
from django.utils import timezone
from django.contrib.auth import get_user_model
from .models import Notification

logger = logging.getLogger(__name__)
User = get_user_model()


class NotificationService:
    """通知服务类"""
    
    @staticmethod
    def create_notification(
        recipient,
        title,
        content,
        notification_type='system',
        priority='normal',
        sender=None,
        related_object_type=None,
        related_object_id=None
    ):
        """
        创建通知
        
        Args:
            recipient: 接收人（User对象）
            title: 通知标题
            content: 通知内容
            notification_type: 通知类型
            priority: 优先级
            sender: 发送人（User对象，可选）
            related_object_type: 关联对象类型
            related_object_id: 关联对象ID
            
        Returns:
            Notification对象或None
        """
        try:
            notification = Notification.objects.create(
                recipient=recipient,
                sender=sender,
                notification_type=notification_type,
                title=title,
                content=content,
                priority=priority,
                related_object_type=related_object_type,
                related_object_id=related_object_id,
                is_sent=True,
                sent_at=timezone.now()
            )
            
            logger.info(f"通知创建成功 - ID: {notification.id}, 接收人: {recipient.username}")
            return notification
            
        except Exception as e:
            logger.error(f"创建通知失败 - 接收人: {recipient.username}, Error: {str(e)}")
            return None
    
    @staticmethod
    def create_ai_evaluation_notification(student_user, resume, job, status, error_message=None):
        """
        创建AI评估相关的通知
        
        Args:
            student_user: 学生用户对象
            resume: 简历对象
            job: 岗位对象
            status: 评估状态 ('completed' 或 'failed')
            error_message: 错误信息（仅在失败时使用）
            
        Returns:
            Notification对象或None
        """
        try:
            if status == 'completed':
                title = "🎉 AI简历评估完成"
                job_title = job.title if job else "目标岗位"
                content = f"""您的简历《{resume.title}》针对《{job_title}》的AI评估已完成！

📊 评估报告已生成，包含：
• 岗位匹配度分析
• 简历优势与不足
• 具体改进建议
• 求职准备指导

💡 立即查看评估结果，让您的简历更具竞争力！

👉 您可以在简历管理页面查看详细报告或直接下载PDF版本。"""

                return NotificationService.create_notification(
                    recipient=student_user,
                    title=title,
                    content=content,
                    notification_type='resume',
                    priority='high',
                    related_object_type='resume',
                    related_object_id=resume.id
                )

            elif status == 'failed':
                title = "⚠️ AI简历评估失败"
                job_title = job.title if job else "目标岗位"

                # 根据错误类型提供不同的建议
                if "内容为空" in (error_message or ""):
                    suggestions = """🔧 建议您：
• 完善简历的基本信息（姓名、联系方式等）
• 添加教育背景和工作经历
• 补充项目经验和技能描述
• 确保简历内容不少于100字"""
                elif "超时" in (error_message or ""):
                    suggestions = """🔧 建议您：
• 稍后重新尝试评估
• 检查网络连接是否稳定
• 如果问题持续，请联系客服"""
                elif "API" in (error_message or ""):
                    suggestions = """🔧 建议您：
• 系统正在维护中，请稍后重试
• 您也可以先完善简历内容
• 如需帮助，请联系客服"""
                else:
                    suggestions = """🔧 建议您：
• 检查简历内容是否完整
• 稍后重新尝试评估
• 如问题持续存在，请联系客服"""

                content = f"""很抱歉，您的简历《{resume.title}》针对《{job_title}》的AI评估遇到了问题。

❌ 失败原因：{error_message or '系统暂时无法处理，请稍后重试'}

{suggestions}

💪 我们会持续优化评估服务，感谢您的理解与支持！"""

                return NotificationService.create_notification(
                    recipient=student_user,
                    title=title,
                    content=content,
                    notification_type='resume',
                    priority='normal',
                    related_object_type='resume',
                    related_object_id=resume.id
                )
                
        except Exception as e:
            logger.error(f"创建AI评估通知失败 - Resume ID: {resume.id}, Error: {str(e)}")
            return None
    
    @staticmethod
    def create_resume_notification(student_user, resume, notification_type, title, content, priority='normal'):
        """
        创建简历相关的通知
        
        Args:
            student_user: 学生用户对象
            resume: 简历对象
            notification_type: 通知类型
            title: 通知标题
            content: 通知内容
            priority: 优先级
            
        Returns:
            Notification对象或None
        """
        return NotificationService.create_notification(
            recipient=student_user,
            title=title,
            content=content,
            notification_type=notification_type,
            priority=priority,
            related_object_type='resume',
            related_object_id=resume.id
        )
    
    @staticmethod
    def create_system_notification(recipient, title, content, priority='normal'):
        """
        创建系统通知
        
        Args:
            recipient: 接收人（User对象）
            title: 通知标题
            content: 通知内容
            priority: 优先级
            
        Returns:
            Notification对象或None
        """
        return NotificationService.create_notification(
            recipient=recipient,
            title=title,
            content=content,
            notification_type='system',
            priority=priority
        )
    
    @staticmethod
    def get_unread_count(user):
        """
        获取用户未读通知数量
        
        Args:
            user: 用户对象
            
        Returns:
            int: 未读通知数量
        """
        try:
            return Notification.objects.filter(
                recipient=user,
                is_read=False
            ).count()
        except Exception as e:
            logger.error(f"获取未读通知数量失败 - User: {user.username}, Error: {str(e)}")
            return 0
    
    @staticmethod
    def mark_as_read(notification_id, user):
        """
        标记通知为已读
        
        Args:
            notification_id: 通知ID
            user: 用户对象
            
        Returns:
            bool: 是否成功
        """
        try:
            notification = Notification.objects.get(
                id=notification_id,
                recipient=user
            )
            notification.is_read = True
            notification.read_at = timezone.now()
            notification.save()
            
            logger.info(f"通知已标记为已读 - ID: {notification_id}, User: {user.username}")
            return True
            
        except Notification.DoesNotExist:
            logger.warning(f"通知不存在或无权限 - ID: {notification_id}, User: {user.username}")
            return False
        except Exception as e:
            logger.error(f"标记通知已读失败 - ID: {notification_id}, Error: {str(e)}")
            return False
    
    @staticmethod
    def mark_all_as_read(user):
        """
        标记用户所有通知为已读
        
        Args:
            user: 用户对象
            
        Returns:
            int: 标记的通知数量
        """
        try:
            count = Notification.objects.filter(
                recipient=user,
                is_read=False
            ).update(
                is_read=True,
                read_at=timezone.now()
            )
            
            logger.info(f"批量标记通知已读 - User: {user.username}, Count: {count}")
            return count
            
        except Exception as e:
            logger.error(f"批量标记通知已读失败 - User: {user.username}, Error: {str(e)}")
            return 0
